package com.shrw.duke.serialport.common.runnable;

import com.shrw.duke.serialport.listener.PortDataListener;
import com.shrw.duke.serialport.utils.PortDataTrimUtils;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by rw-duke on 2018/4/2.
 */

public class PortReadRunnable implements Runnable {
    private static final String TAG = PortReadRunnable.class.getSimpleName();

    private boolean stop;
    private byte[] mBuffer;
    private InputStream mInput;
    private PortDataListener mPortDataListener;

    private PortDataTrimUtils mPortDataTrimUtils;

    public PortReadRunnable(FileDescriptor fileDescriptor, PortDataListener portDataListener) {
        mPortDataListener = portDataListener;
        mInput = new FileInputStream(fileDescriptor);
        mPortDataTrimUtils = PortDataTrimUtils.getInstance();
    }

    @Override
    public void run() {
        try {
            boolean addSuccess;
            byte[] buffer;
            while (!stop) {
                mBuffer = new byte[512];
                int length = this.mInput.read(mBuffer);
                //验证数据
//                Log.e(TAG, HexUtils.toHexString(mBuffer, mBuffer.length).toString());
                addSuccess = mPortDataTrimUtils.add(mBuffer, length);
                if (addSuccess) {
                    buffer = mPortDataTrimUtils.get();
                    if (buffer != null) {
                        mPortDataListener.onPortData(buffer);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                mInput.close();
                mBuffer = null;
                mPortDataTrimUtils = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     */
    public void stop() {
        stop = true;
    }
}
